package rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1. 创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("121.199.172.18");
        factory.setPort(5672);//需要提前开放端口号
        factory.setUsername("study");
        factory.setPassword("ddup");
        factory.setVirtualHost("study");
        Connection connection = factory.newConnection();
        //2. 创建channel
        Channel channel = connection.createChannel();
        //3. 声明队列（此处可省略）
        channel.queueDeclare("hello",true,false,false,null);
        //4. 消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            //从队列中收到消息会执行的方法
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //TODO
                System.out.println("接收到消息：" + new String(body));
            }
        };
        /**
         * String basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数介绍：
         * queue: 队列名
         * autoAck: 是否自动确认
         * callback: 接收到消息后执行的逻辑
         */
        channel.basicConsume("hello",true,consumer);
        System.out.println("接收到消息");
        //5. 释放资源
        Thread.sleep(3000);
        channel.close();
        connection.close();

    }
}
